package cn.hpclub.server.service;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.plugin.activerecord.Db;

import cn.hpclub.server.model.Brand;
import cn.hpclub.server.util.QueryHelper;

public class BrandService{
    public static final BrandService service = new BrandService();

    /**
     * 
     * @Title: getQueryHelper
     * @Description:生成一个QueryHelper，用于辅助生成select和sqlExceptSelect 语句
     * @param searchInfo
     * @return QueryHelper
     */
    public QueryHelper getQueryHelper(ConcurrentHashMap<String, String> searchInfo){
        /*
         * QueryHelper helper = new QueryHelper("select *",Brand.class,"b")
         * .addCondition(searchInfo.containsKey("name"),"b.name like ?",
         * "%"+searchInfo.get("name")+"%")
         * .addCondition(searchInfo.containsKey("starttime"),"b.create_time >=?
         * ", searchInfo.get("starttime"))
         * .addCondition(searchInfo.containsKey("endtime"),"b.create_time <=?",
         * searchInfo.get("endtime"));
         */
        // 以后还需要来优化QueryHelper，以支持join on语句
        QueryHelper helper = new QueryHelper(
                "select b.id,b.name,b.create_time,s.user_name as operated_by,b.operated_time,b.description,b.enabled",
                "brand b left join sys_user s on b.operated_by=s.id")
                        .addCondition("b.enabled=?", 1)
                        .addCondition(searchInfo.containsKey("name"), "b.name like ?",
                                      "%" + searchInfo.get("name") + "%")
                        .addCondition(searchInfo.containsKey("starttime"), "b.create_time >=?",
                                      searchInfo.get("starttime") + " 00:00:00")
                        .addCondition(searchInfo.containsKey("endtime"), "b.create_time <=?",
                                      searchInfo.get("endtime") + " 23:59:59")
                        .addOrderProperty("b.operated_time", false);

        return helper;
    }

    /**
     * 
     * @Title: changeStatus
     * @Description:修改品牌的状态
     * @param id
     * @param targetStatus
     * @return boolean
     */
    public boolean changeStatus(String id, String targetStatus){
        String sql = "";
        if(targetStatus.equalsIgnoreCase("1")){
            sql = "update brand set enabled = 1 where id=?";
        } else{
            sql = "update brand set enabled = 0 where id=?";
        }

        return Db.update(sql, id) > 0;
    }

    /**
     * @Title: findAll
     * @Description:获取所有的品牌
     */

    public List<Brand> findAll(){
        return Brand.dao.find("select * from brand");
    }

    /**
     * @Title: getAllEnabledBrands
     * @return Brand
     */
    public List<Brand> getAllEnabledBrands(){
        String sql = "select * from brand where enabled=1 order by operated_time";
        return Brand.dao.find(sql);
    }
}
